from django.contrib.auth.backends import ModelBackend
from django_acl.models import has_named_permission
import re

_django_permission = re.compile(r'^(.+).(add|change|delete)_(\w+)$')

class ACLBackend(ModelBackend):
  
  def get_all_permissions(self, user_obj):
    raise Exception, "Should not be called"
  
  def cached_perm(self, user_obj, perm):
    if not hasattr(user_obj, '_cached_acl_perms'):
      user_obj._cached_acl_perms = {}
      
    if not perm in user_obj._cached_acl_perms:
      user_obj._cached_acl_perms[perm] = has_named_permission(user_obj, perm)
    
    #print perm, user_obj._cached_acl_perms[perm]
    return user_obj._cached_acl_perms[perm]
  
  def has_module_perms(self, user_obj, app_label):
    return self.cached_perm(user_obj, '%s.can_read' % app_label)
    
  def has_perm(self, user_obj, perm):
    m = _django_permission.match(perm)
    if m:
      perm = "%s.%s.can_%s" % (m.group(1), m.group(3), m.group(2))
      
    return self.cached_perm(user_obj, perm)
    